import requests
from loguru import logger
import urllib3
from multiprocessing.managers import ValueProxy

# 禁用不安全请求的警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class GlobalProxyManager:
    def __init__(self, shared_proxy: ValueProxy):
        self.shared_proxy = shared_proxy
    
    def get_new_proxy(self):
        """获取新代理"""
        try:
            requests.adapters.DEFAULT_RETRIES = 5
            s = requests.session()
            s.keep_alive = False
            response = s.get(
                'https://kps.kdlapi.com/api/getkps/?secret_id=odelx3snscvth9qe5vbo&signature=7sbc7nptox3edlc1kxepgdq0cq4nx1c0&num=1&pt=1&format=text&sep=1',
                verify=False  # 如果确实需要跳过证书验证
            )
            proxy = response.text.strip()
            if 'req over limit' in proxy:
                return self.shared_proxy.value
            else:
                self.shared_proxy.value = proxy
                logger.info(f"更新代理: {proxy}")
                return proxy
        except Exception as e:
            logger.error(f"获取新代理失败: {e}")
            return None

    def get_proxy(self):
        """获取当前代理"""
        return self.shared_proxy.value 